<?php

namespace AppBundle\Controller\Admin;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class IndexController extends BaseController
{
    /**
     * admin panel
     * 
     */
    public function indexAction(Request $request)
    {
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
            throw $this->createAccessDeniedException();
        }
     
//        $user = $this->getUser();dump( $user);die;
        # render login page
        return $this->render('admin/index/index.html.twig');
    }

    /**
     * admin dashboard
     * 
     */
    public function dashboardAction(Request $request)
    {
        # render login page
        $em = $this->getDoctrine()->getManager();
 
        $qb = $em->getRepository('AppBundle:Pages')->createQueryBuilder('p');
    
        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate($qb, $request->query->getInt('page', 1),9);
        return $this->render('admin/index/main.html.twig', [
            'pagination' => $pagination,
        ]);
    }

    /**
     * administor setting
     * 
     */
    public function settingAction(Request $request)
    { 
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
            throw $this->createAccessDeniedException();
        }
        return $this->render('admin/index/setting.html.twig');
    }

    /**
     * administor setting
     * 
     */
    public function settingStoreAction(Request $request)
    {
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
            throw $this->createAccessDeniedException();
        }
        $user = $this->getUser();
        $old = $request->get('old','');
        $newpwd1 = $request->get('newpwd1','');
        $newpwd2 = $request->get('newpwd2','');
        $encoder = $this->get('security.password_encoder');
        
        if (!$newpwd1||$newpwd1!=$newpwd2) {
            $return['errno'] = 1;
            $return['message'] = "新密码不一致";
        } else {
            $true = $encoder->isPasswordValid($user,$old);
            if($true){
                $encoded = $encoder->encodePassword($user,$newpwd1);
                $user->setPassword($encoded);
                $em = $this->getDoctrine()->getManager();
                $em->persist($user);
                $em->flush();
                $return['errno'] = 0;
                $return['message'] = "成功";
            } else {
                $return['errno'] = 1;
                $return['message'] = "旧密码不正确";
            }
        }
        return $this->json($return, 200);
    }
}

    